package com.heima.wemedia.controller.v1;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.pojos.ApArticle;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.wemedia.pojos.WmUser;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/user")
public class UserController {

    @Autowired
    private WmUserService wmUserService;

    /**
     * 开通自媒体用户
     *
     * @param wmUser 用户信息
     * @return 返回结果
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody WmUser wmUser) {
        wmUserService.save(wmUser);
        return ResponseResult.okResult(null);
    }

    /**
     * 查询自媒体用户
     *
     * @param wmUser 前端dto (根据app端用户id或app端用户名称查询)
     * @return 查询结果
     */
    @PostMapping("/sel")
    public ResponseResult<WmUser> getUser(@RequestBody WmUser wmUser) {
        //参数校验
        if (wmUser.getApUserId() == null && wmUser.getName() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        if (wmUser.getApUserId() != null && wmUser.getName() == null) {
            //根据app端用户id查询
            wrapper.eq(WmUser::getApUserId, wmUser.getApUserId());
        } else if ((wmUser.getName() != null && wmUser.getApUserId() == null)) {
            //根据app端用户名称查询
            wrapper.eq(WmUser::getName, wmUser.getName());
        }
        WmUser user = wmUserService.getOne(wrapper);
        return ResponseResult.okResult(user);
    }

    /**
     * 修改自媒体用户
     * 根据自媒体用户名称修改关联的app端用户id
     *
     * @param wmUser 前端的自媒体用户名称和app端用户id
     * @return 返回结果
     */
    @PostMapping("/update")
    public ResponseResult updateUser(@RequestBody WmUser wmUser) {
        LambdaUpdateWrapper<WmUser> wrapper4 = new LambdaUpdateWrapper<>();
        wrapper4.set(WmUser::getApUserId, wmUser.getApUserId())
                .eq(WmUser::getId, wmUser.getId());
        wmUserService.update(wrapper4);
        return ResponseResult.okResult(null);
    }
}
